package com.hxcoder.mail.controller;

import com.hxcoder.commonutils.R;
import com.hxcoder.mail.service.MailService;
import com.hxcoder.mail.utils.RandomUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @author hxcoder
 */
@Api(tags = "验证码管理")
@RestController
@RequestMapping("/mail")
public class MailController {

    @Autowired
    private MailService mailService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @ApiOperation(value = "发送验证码", notes = "通过邮件发送验证码")
    @GetMapping("send/{mailAcc}")
    public R sendMsm(@PathVariable String mailAcc) {

        //1 从redis获取验证码，如果获取到直接返回
        String code = redisTemplate.opsForValue().get(mailAcc);
        if (!StringUtils.isEmpty(code)) {
            return R.ok();
        }

        //2 如果redis获取不到，进行邮件发送
        code = RandomUtil.getFourBitRandom();
        boolean isSend = mailService.send(mailAcc, "星空学院验证码", "欢迎注册星空学院，您的验证码是：" + code + "。请在5分钟内完成注册");
        if (isSend) {
            //发送成功，把发送成功验证码放到redis里面
            //设置有效时间
            redisTemplate.opsForValue().set(mailAcc, code, 5, TimeUnit.MINUTES);
            return R.ok();
        } else {
            return R.error().message("验证码发送失败");
        }
    }
}